<template>
  <div class="device-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>设备列表</span>
          <div class="header-actions">
            <el-input
              v-model="searchForm.keyword"
              placeholder="搜索设备ID或名称"
              style="width: 200px; margin-right: 10px;"
              clearable
            />
            <el-button type="primary" @click="searchDevices">搜索</el-button>
          </div>
        </div>
      </template>
      
      <el-table :data="deviceList" v-loading="loading" stripe>
        <el-table-column prop="id" label="设备ID" width="180" />
        <el-table-column prop="name" label="设备名称" width="150" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'online' ? 'success' : row.status === 'maintenance' ? 'warning' : 'info'">
              {{ row.status === 'online' ? '在线' : row.status === 'maintenance' ? '维护中' : '离线' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="user_nickname" label="绑定用户" width="120" />
        <el-table-column prop="last_heartbeat" label="最后心跳" width="180">
          <template #default="{ row }">
            {{ formatDate(row.last_heartbeat) }}
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button size="small" @click="viewDeviceLogs(row.id)">查看日志</el-button>
            <el-button size="small" type="danger" @click="disconnectDevice(row.id)">断开连接</el-button>
            <el-dropdown @command="handleDeviceAction">
              <el-button size="small" type="warning">
                更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="{action: 'lock', deviceId: row.id}">
                    锁定设备
                  </el-dropdown-item>
                  <el-dropdown-item :command="{action: 'unlock', deviceId: row.id}">
                    解锁设备
                  </el-dropdown-item>
                  <el-dropdown-item :command="{action: 'maintenance', deviceId: row.id}">
                    设置维护
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getDeviceList, disconnectDevice, lockDevice, unlockDevice, setDeviceMaintenance } from '@/api/device'
import { formatDate } from '@/utils/format'

interface Device {
  id: string
  name: string
  status: 'online' | 'offline'
  user_nickname: string
  last_heartbeat: string
  created_at: string
}

const router = useRouter()
const loading = ref(false)
const deviceList = ref<Device[]>([])

const searchForm = reactive({
  keyword: ''
})

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const loadDeviceList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      keyword: searchForm.keyword
    }
    const response = await getDeviceList(params)
    deviceList.value = response.data.records
    pagination.total = response.data.total
  } catch (error) {
    ElMessage.error('获取设备列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

const searchDevices = () => {
  pagination.currentPage = 1
  loadDeviceList()
}

const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  loadDeviceList()
}

const handleCurrentChange = (val: number) => {
  pagination.currentPage = val
  loadDeviceList()
}

const viewDeviceLogs = (deviceId: string) => {
  router.push(`/devices/logs/${deviceId}`)
}

const handleDisconnectDevice = async (deviceId: string) => {
  try {
    await ElMessageBox.confirm('确定要断开该设备的连接吗？', '提示', {
      type: 'warning'
    })
    
    await disconnectDevice(deviceId)
    ElMessage.success('设备已断开连接')
    loadDeviceList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('断开设备连接失败')
      console.error(error)
    }
  }
}

const handleDeviceAction = async ({ action, deviceId }) => {
  try {
    switch (action) {
      case 'lock':
        await ElMessageBox.confirm(
          '确定要锁定该设备吗？锁定后设备将无法使用。',
          '确认锁定设备',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        await lockDevice(deviceId)
        ElMessage.success('设备已锁定')
        loadDeviceList()
        break
        
      case 'unlock':
        await ElMessageBox.confirm(
          '确定要解锁该设备吗？',
          '确认解锁设备',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        await unlockDevice(deviceId)
        ElMessage.success('设备已解锁')
        loadDeviceList()
        break
        
      case 'maintenance':
        await ElMessageBox.confirm(
          '确定要将该设备设置为维护状态吗？',
          '确认设置维护状态',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        await setDeviceMaintenance(deviceId, true)
        ElMessage.success('设备已设置为维护状态')
        loadDeviceList()
        break
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败: ' + (error.message || '未知错误'))
      console.error(error)
    }
  }
}

onMounted(() => {
  loadDeviceList()
})
</script>

<style scoped lang="scss">
.device-list {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>